package com.huatai.exchange.utils;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.ListUtils;
import com.faneui.dal.DBUtils;
import com.faneui.service.Dbconfig;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

@Service
public class GzbUtils {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public String checkGzbIsFinish(String ztbh, String occurDate) throws BusinessException {
        logger.info("校验估值表是否生成");
        Connection conn = null;
        String user = "facx";
        String r = null;
        try {
            conn = DBUtils.getConnection(Dbconfig.FATADB, user, Dbconfig.getPasswordByUserId(user));
            String[] ztbhs = ztbh.split(",");
            String sql = " select 1 from hsfa.vjk_wbfk_gzb where l_sfqr = 1 and l_ztbh = ? and d_ywrq = to_date(?,'yyyymmdd') ";
            for (String z : ztbhs) {
                List<Map<String, Object>> result = DBUtils.executeQuery(conn, sql, z, occurDate);
                r = ListUtils.isEmpty(result) ? "编号[" + ztbh + "]估值表未生成" : "1";
                if (!"1".equals(r)) {
                    break;
                }
            }
        } catch (Exception ex) {
            logger.error("", ex);
            r = ex.getMessage();
        } finally {
            DBUtils.closeAll(conn);
        }
        logger.info("校验估值表是否生成");
        return r;

    }

    @Deprecated
    public String checkGzbIsFinishAndConfirm(String ztbh, String occurDate) throws BusinessException {
        return checkGzbIsFinish(ztbh, occurDate);
    }

    public List<Map<String, Object>> getFundNavList(String ztbh, String startDate, String endDate) throws BusinessException {
        if (StringUtils.isBlank(startDate)) {
            startDate = "20000101"; // 从两千年开始
        }
        Connection conn = null;
        String user = "facx";
        List<Map<String, Object>> result = null;
        try {
            conn = DBUtils.getConnection(Dbconfig.FATADB, user, Dbconfig.getPasswordByUserId(user));
            StringBuffer sql = new StringBuffer(" select to_char(d_ywrq, 'yyyy-mm-dd') d_date,                                                                \n");
            sql.append("        to_char(sum(decode(vc_kmdm, '今日单位净值:', to_number(vc_kmmc), 0)),'0.0000') f_netvalue,           \n");
            sql.append("        to_char(sum(decode(vc_kmdm, '今日单位净值:', to_number(vc_kmmc), 0)),'0.0000') f_totalnetvalue       \n");
            sql.append("   from hsfa.vjk_wbfk_gzb t                                                                                       \n");
            sql.append("  where t.l_ztbh = ?  and d_ywrq >= to_date(?,'yyyymmdd')                                     \n");
            sql.append("    and d_ywrq <= to_date(?,'yyyymmdd') and vc_kmdm in ('今日单位净值:', '累计单位净值:')                    \n");
            sql.append("  group by d_ywrq                                                                                            \n");
            sql.append("  order by d_ywrq desc ");
            result = DBUtils.executeQuery(conn, sql.toString(), ztbh, startDate, endDate);
        } catch (Exception ex) {
            logger.error("", ex);
        } finally {
            DBUtils.closeAll(conn);
        }
        return result;
    }

    /**
     * 获取 估值表指标
     */
    public String getGzbQuota(String ztbh, String occurDate, String quotaName) throws BusinessException {
        Connection conn = null;
        String user = "facx";
        String r;
        String field = "";
        if ("今日单位净值".equals(quotaName)) {
            field = "今日单位净值:";
        } else if ("累计净值".equals(quotaName)) {
            field = "累计单位净值:";
        } else if ("年净值增长率".equals(quotaName)) {
            field = "净值年增长率(%):";
        } else if ("日净值增长率".equals(quotaName)) {
            field = "净值日增长率(%):";
        } else {
            field = quotaName;
        }
        try {
            conn = DBUtils.getConnection(Dbconfig.FATADB, user, Dbconfig.getPasswordByUserId(user));
            String sql = " select vc_kmmc result from hsfa.vjk_wbfk_gzb where l_sfqr = 1 and l_ztbh = ?" +
                    " and d_ywrq = to_date(?,'yyyymmdd')  and vc_kmdm = ? ";
            List<Map<String, Object>> result = DBUtils.executeQuery(conn, sql, ztbh, occurDate, field);
            if (ListUtils.isEmpty(result)) {
                throw new BusinessException("编号[" + ztbh + "]估值表未出");
            }
            return (String) result.get(0).get("RESULT");
        } catch (Exception ex) {
            logger.error("", ex);
            r = ex.getMessage();
        } finally {
            DBUtils.closeAll(conn);
        }
        return r;
    }

    public String getGzbQuotaStr(String ztbh, String occurDate, String quotaName) throws BusinessException {
        String str = "";
        String str1 = "";
        if ("今日单位净值".equals(quotaName)) {
            str = "单位净值：";
        } else if ("累计净值".equals(quotaName)) {
            str = "累计净值：";
        } else if ("年净值增长率".equals(quotaName)) {
            str = "今年以来收益率: ";
            str1 = "%";
        } else if ("日净值增长率".equals(quotaName)) {
            str = "日净值增长率：";
            str1 = "%";
        } else {
            str = quotaName;
        }
        String result = getGzbQuota(ztbh, occurDate, quotaName);
        return str + result + str1;
    }

    public String getGzbQuotasStr(String ztbh, String occurDate, List<String> quotaNames) throws BusinessException {
        if (ListUtils.isEmpty(quotaNames))
            return null;
        StringBuffer sb = new StringBuffer("");
        for (String quotaName : quotaNames) {
            sb.append(" ").append(getGzbQuotaStr(ztbh, occurDate, quotaName));
        }
        return sb.toString();
    }

    public String getGzbQuotasStr(String ztbh, String occurDate, String quotaNames) throws BusinessException {
        if (StringUtils.isBlank(quotaNames))
            return null;
        return getGzbQuotasStr(ztbh, occurDate, Lists.newArrayList(quotaNames.split(",")));
    }

    @Deprecated
    public String getGzbQuotaNoConfirm(String ztbh, String occurDate, String quotaName) throws BusinessException {
        return getGzbQuota(ztbh, occurDate, quotaName);
    }

    public List<Map<String, Object>> executeSqlQuery(String sql, String... params) throws BusinessException {
        Connection conn = null;
        String user = "facx";
        try {
            conn = DBUtils.getConnection(Dbconfig.FATADB, user, Dbconfig.getPasswordByUserId(user));
            return DBUtils.executeQuery(conn, sql, params);
        } catch (Exception ex) {
            logger.error("", ex);
        } finally {
            DBUtils.closeAll(conn);
        }
        return null;
    }

}
